﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using blackhouse;

namespace blackhouse.BlackApart.Business.MailTemplate {
	public class MailTemplateFile {

		#region Fields

		private DirectoryInfo directoryForAscxControls;
		private DirectoryInfo wwwDirectory;
		private string language = "";

		#endregion

		#region Constructors

		public MailTemplateFile(DirectoryInfo directoryForAscxControls, DirectoryInfo wwwDirectory, string language) {
			this.directoryForAscxControls = directoryForAscxControls;
			this.wwwDirectory = wwwDirectory;
			this.language = language;
		}

		#endregion

		#region Methods

		public void CreateOrUpdateIfNewest(IMailTemplate mailTemplate) {
			FileInfo ascx = this.GetAscxFile(mailTemplate);
			if (!ascx.Exists || ascx.LastWriteTime < mailTemplate.LastUpdateTime)
				this.UpdateLocalAscx(mailTemplate, ascx);
		}

		private void UpdateLocalAscx(IMailTemplate mailTemplate, FileInfo localAscx) {
			using (FileStream fs = localAscx.Open(FileMode.Create, FileAccess.Write))
			using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) {
				sw.Write(mailTemplate.TemplateControl);
			}
		}

		private FileInfo GetAscxFile(IMailTemplate mailTemplate) {
			return new FileInfo(directoryForAscxControls.FullName + @"\" + mailTemplate.Id + "-" + this.language + ".ascx");
		}

		public string GetControlFilePath(IMailTemplate mailTemplate) {
			return ("~/" + this.GetAscxFile(mailTemplate).FullName.ReplaceEx(this.wwwDirectory.FullName, "")).ReplaceEx(@"\", "/");
		}

		#endregion

	}
}
